package com.xgkj.diyiketang.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.task.BangdingWeixinTask;
import com.xgkj.diyiketang.task.TiXianTask;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.eatshow.wxapi.WXEntryActivity;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DecimalFormat;

/**
 * Created by XCKJ_Paladowow on 2016/4/15.
 */
public class TiXianActivity extends BaseActivity implements View.OnClickListener{

    private Context mContext;
    private TextView back;
    private TextView mKTXText;
//    private EditText mZfbEdit;
//    private String mZfbString;
    private String yue;
    private EditText mNameEdit;
    private String nameString;
    private TextView jineText;
    private String jineString;
    private Button sureBtn;
    private RelativeLayout mJineLayout;
    private PopupWindow boPopWindow;
    private TextView jinbiText;
    private RelativeLayout jinbiLayout;
    private ImageView jinbiDivider;
    private int from;
    private String realLiveCoin;
    private double canWithdrawRmb;
    private int type = 0;
    private TextView jineTitleText;
    private EatShowUserInfo userInfo;
    private String oldNickname;
    private String haveBindWx;
    private int tixiantaskId = -1;
    private int bangdingWeixinTaskId = -1;

    private RelativeLayout weixinNickLayout;
    private TextView wxNickname;
    private RelativeLayout noBindWxLayout;
    private TextView goBindBtn;

    private IWXAPI wxApi = null;
    private WeiXinReceiver wxReceiver;
    private String openidString;
    private String nicknameString;

    private InputMethodManager inputMethodManager;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tixian);
        mContext = this;
        initView();
        wxApi = WXAPIFactory.createWXAPI(getApplicationContext(), null);
        wxApi.registerApp(ProtocolConst.APP_ID);
        inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

    }

    private void initView(){
        back = (TextView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        Intent intent = getIntent();
        if (intent != null) {
            yue = intent.getStringExtra("YUE");
            from = intent.getIntExtra("from",0);
            realLiveCoin = intent.getStringExtra("realLiveCoin");
        }
        jinbiLayout = (RelativeLayout) findViewById(R.id.huaduo_layout);
        jinbiDivider = (ImageView) findViewById(R.id.huaduo_divider);
        jinbiText = (TextView) findViewById(R.id.tixian_huaduo);
        jineTitleText = (TextView) findViewById(R.id.jine_title);
        mKTXText = (TextView) findViewById(R.id.tixian_jine);
//        mZfbEdit = (EditText) findViewById(R.id.tixian_zfb_content);
        mNameEdit = (EditText) findViewById(R.id.tixian_name_content);
        jineText = (TextView) findViewById(R.id.jine_content);
        mJineLayout = (RelativeLayout) findViewById(R.id.jine_layout);
        mJineLayout.setOnClickListener(this);
        sureBtn = (Button) findViewById(R.id.tixian_btn);
        sureBtn.setOnClickListener(this);
        weixinNickLayout = (RelativeLayout) findViewById(R.id.weixin_nick_layout);
        wxNickname = (TextView) findViewById(R.id.wx_nickname);
        noBindWxLayout = (RelativeLayout) findViewById(R.id.no_bind_wx_layout);
        goBindBtn = (TextView) findViewById(R.id.go_bind_btn);
        goBindBtn.setOnClickListener(this);
        initBOPopWindow();

        if (from ==0){
            type = 0;
            mKTXText.setText(yue);
            jinbiLayout.setVisibility(View.GONE);
            jinbiDivider.setVisibility(View.GONE);
            jineTitleText.setText(R.string.ketixian_jine);
        }else if (from ==1){
            type = 1;
            jinbiLayout.setVisibility(View.VISIBLE);
            jinbiDivider.setVisibility(View.VISIBLE);
            jineTitleText.setText(R.string.keduihuan_jine);
            if (!ViewUtil.isNull(realLiveCoin)) {
                jinbiText.setText(realLiveCoin);
                try {
                    canWithdrawRmb = Double.parseDouble(realLiveCoin);
                    canWithdrawRmb = canWithdrawRmb / 10;
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
            DecimalFormat format = new DecimalFormat("0.00");
            String ss = format.format(canWithdrawRmb);
            mKTXText.setText(ss);
        }

        userInfo = getEatShowApp().getmUserInfo();
        if (userInfo != null){
            oldNickname = userInfo.getOldNickname();
            haveBindWx = userInfo.getHaveBindPay();
            if (haveBindWx.equals("1")){
                weixinNickLayout.setVisibility(View.VISIBLE);
                noBindWxLayout.setVisibility(View.GONE);
                try {
                    oldNickname = URLDecoder.decode(oldNickname,"utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                wxNickname.setText(oldNickname);
            }else {
                weixinNickLayout.setVisibility(View.GONE);
                noBindWxLayout.setVisibility(View.VISIBLE);
            }
        }

    }

    private void initBOPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.pop_tixian,null);
        view.findViewById(R.id.money100).setOnClickListener(this);
        view.findViewById(R.id.money1000).setOnClickListener(this);
        view.findViewById(R.id.money2000).setOnClickListener(this);
        view.findViewById(R.id.money5000).setOnClickListener(this);
        view.findViewById(R.id.money10000).setOnClickListener(this);
        boPopWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        boPopWindow.setBackgroundDrawable(new ColorDrawable());
        boPopWindow.setFocusable(true);
        boPopWindow.setOutsideTouchable(true);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.jine_layout:
                try {
                    inputMethodManager.hideSoftInputFromWindow(TiXianActivity.this.getCurrentFocus().getWindowToken(),0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                boPopWindow.showAtLocation(v, Gravity.BOTTOM,0,0);
                break;
            case R.id.money100:
                jineText.setText("100");
                jineString = "100";
                boPopWindow.dismiss();
                break;
            case R.id.money1000:
                jineText.setText("1000");
                jineString = "1000";
                boPopWindow.dismiss();
                break;
            case R.id.money2000:
                jineText.setText("2000");
                jineString = "2000";
                boPopWindow.dismiss();
                break;
            case R.id.money5000:
                jineText.setText("5000");
                jineString = "5000";
                boPopWindow.dismiss();
                break;
            case R.id.money10000:
                jineText.setText("10000");
                jineString = "10000";
                boPopWindow.dismiss();
                break;
            case R.id.tixian_btn:
                if(checkInput()){
                    doTiXian();

                }
                break;
            case R.id.go_bind_btn:
                ViewUtil.showProgressDialog(mContext,getString(R.string.get_pageinfo_loading),-1);
                sendWxAuthRequest();
                break;
        }
    }

    private void doTiXian(){
        TiXianTask task = new TiXianTask(jineString,null,nameString,type);
        task.addListener(new TiXianListener(mContext));
        tixiantaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private void bindWxPay(){
        BangdingWeixinTask bangdingWeixinTask = new BangdingWeixinTask(openidString,nicknameString);
        bangdingWeixinTask.addListener(new TiXianListener(mContext));
        bangdingWeixinTaskId = getEatShowApp().getTaskManager().addTask(bangdingWeixinTask);
    }

    class TiXianListener extends ShowToastTaskEventListener {

        public TiXianListener(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId ==tixiantaskId) {
                Intent tjIntent = new Intent(mContext, ChuangJianChengGongActivity.class);
                tjIntent.putExtra("FROM", "TIXIAN");
                startActivity(tjIntent);
                finish();
            }else if (taskId == bangdingWeixinTaskId){
                weixinNickLayout.setVisibility(View.VISIBLE);
                noBindWxLayout.setVisibility(View.GONE);
                wxNickname.setText(nicknameString);
                oldNickname = nicknameString;
                if (userInfo != null){
                    userInfo.setOldNickname(oldNickname);
                    userInfo.setHaveBindPay("1");
                }
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    }


    private boolean checkInput() {
//        mZfbString = mZfbEdit.getText().toString();
        double tixianjine = 0.0;
        try {
            tixianjine = Double.parseDouble(jineString);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        nameString = mNameEdit.getText().toString();
//        if (TextUtils.isEmpty(mZfbString)) {
//            Toast.makeText(mContext, "请输入您的支付宝账户", Toast.LENGTH_SHORT)
//                    .show();
//            return false;
//        }else

        if (TextUtils.isEmpty(oldNickname)){
            Toast.makeText(mContext, R.string.please_bind_wx_first, Toast.LENGTH_SHORT)
                    .show();
            return false;
        }

        if(TextUtils.isEmpty(nameString)){
            Toast.makeText(mContext, "请输入您的真实姓名", Toast.LENGTH_SHORT)
                    .show();
            return false;

        }

        if(TextUtils.isEmpty(jineString)){
            Toast.makeText(mContext, "请选择您要提现的金额", Toast.LENGTH_SHORT)
                    .show();
            return false;
        }

        if(from == 0){
            double ktxYue = 0.0;
            try {
                ktxYue = Double.parseDouble(yue);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            if (tixianjine > ktxYue) {
                Toast.makeText(mContext, "提现金额不能大于您的余额", Toast.LENGTH_SHORT)
                        .show();
                return false;
            }
        }else if (from == 1){
            if (tixianjine >canWithdrawRmb){
                Toast.makeText(mContext,"提现金额不能大于您的可兑换金额",Toast.LENGTH_SHORT).show();
                return false;
            }
        }

        return true;
    }


    /**
     * 绑定微信
     */
    private void sendWxAuthRequest() {

        if (wxApi.isWXAppInstalled()) {
            if (wxReceiver == null) {
                wxReceiver = new WeiXinReceiver();
                IntentFilter filter = new IntentFilter();
                filter.addAction(WXEntryActivity.WEIXIN_LOGIN_SUCCESS_ACTION);
                registerReceiver(wxReceiver, filter);
            }
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";
            req.state = "wechat_sdk_demo";
            //拉起微信授权，授权结果在WXEntryActivity中接收处理
            wxApi.sendReq(req);
        } else {
            Toast.makeText(this, "微信未安装", Toast.LENGTH_SHORT).show();
        }
    }


    class WeiXinReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(WXEntryActivity.WEIXIN_LOGIN_SUCCESS_ACTION)) {
                if (wxReceiver != null) {
                    unregisterReceiver(wxReceiver);
                    wxReceiver = null;
                }
                openidString = intent.getStringExtra(ProtocolConst.WEIXIN_OPENID);
                nicknameString = intent.getStringExtra("NICK");
                bindWxPay();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        ViewUtil.dismissDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (wxReceiver != null){
            unregisterReceiver(wxReceiver);
            wxReceiver = null;
        }
    }
}
